﻿using Avalon.Core.Data;
using Avalon.Core.MVC.Attributes;
using Avalon.Core.MVC.StateBags;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace Avalon.Core.MVC.Actions
{
    [PipelineAction("OrderEntityAction")]
    public sealed class OrderEntityAction<TModel> : IPipelineAction where TModel : class, IEntity, new()
    {
        public int Index { get; set; }
        public void Execute(ICollectionBag<TModel> stateBag)
        {
            try
            {
                ICollectionBag<TModel> bag = (ICollectionBag<TModel>)stateBag;
                ParameterExpression parameterExpression = Expression.Parameter(typeof(TModel));
                Expression constantExpression = Expression.Property(parameterExpression, stateBag.ParameterValues["Parameter"].ToString());
                Expression<Func<TModel, string>> lambda = (Expression<Func<TModel, string>>)Expression.Lambda(constantExpression, parameterExpression);

                bag.Models = bag.Models.OrderBy<TModel, string>(lambda).AsQueryable<TModel>();
            }
            catch (Exception ex)
            {
                stateBag.Error = new Exception(string.Format("Get entites name: {0}", typeof(TModel).Name), ex);
            }
        }

        public void Execute(IStateBag stateBag)
        {
            Execute((ICollectionBag<TModel>)stateBag);
        }
    }
}
